package com.cool.modules.finance.service.order.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cool.core.base.BaseServiceImpl;
import com.cool.core.exception.CoolException;
import com.cool.core.util.CoolSecurityUtil;
import com.cool.modules.finance.constant.OrderType;
import com.cool.modules.finance.dto.FinancePaymentAccountVo;
import com.cool.modules.finance.entity.account.FinanceAccountEntity;
import com.cool.modules.finance.entity.category.FinanceCategoryEntity;
import com.cool.modules.finance.entity.coin.FinanceCoinEntity;
import com.cool.modules.finance.entity.family.FinanceUserFamilyEntity;
import com.cool.modules.finance.entity.order.FinanceOrderEntity;
import com.cool.modules.finance.entity.order.FinanceOrderImgEntity;
import com.cool.modules.finance.mapper.order.FinanceOrderMapper;
import com.cool.modules.finance.service.account.FinanceAccountService;
import com.cool.modules.finance.service.category.FinanceCategoryService;
import com.cool.modules.finance.service.coin.FinanceCoinService;
import com.cool.modules.finance.service.family.FinanceUserFamilyService;
import com.cool.modules.finance.service.order.FinanceOrderImgService;
import com.cool.modules.finance.service.order.FinanceOrderService;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class FinanceOrderServiceImpl extends BaseServiceImpl<FinanceOrderMapper, FinanceOrderEntity> implements FinanceOrderService {

    final FinanceAccountService accountService;

    final FinanceCategoryService categoryService;

    final FinanceUserFamilyService userFamilyService;

    final FinanceOrderImgService orderImgService;

    final FinanceCoinService coinService;

    @Override
    public Long add(FinanceOrderEntity entity) {
        entity.setOrderType(OrderType.getByValue(entity.getOrderTypeValue()));
        Optional<FinanceUserFamilyEntity> first = userFamilyService.list(new QueryWrapper().eq(FinanceUserFamilyEntity::getUserId, CoolSecurityUtil.getCurrentUserId())).stream().findFirst();
        if (first.isEmpty()){
            throw new RuntimeException("当前账户没有家庭分组，暂时无法记账，请加入家庭后重试");
        }
        entity.setFamilyId(first.get().getFamilyId());
        // 校验余额并支付
        FinancePaymentAccountVo params = new FinancePaymentAccountVo();
        BeanUtil.copyProperties(entity, params);
        accountService.checkBalanceAndPayment(params);
        entity.setOrderDate(null==entity.getOrderDate()?new Date() :entity.getOrderDate());
        entity.setCreateUser(CoolSecurityUtil.getCurrentUserId());

        FinanceCoinEntity coin = coinService.getById(accountService.getById(entity.getAccountId()).getCoinId());
        if (coin != null){
            entity.setCoinId(coin.getId());
            entity.setCoinSymbol(coin.getSymbol());
        }

        //保存账目记录
        Long add = super.add(entity);
        if(null!=entity.getImageList()) {
            orderImgService.updateImgList(add, entity.getImageList().stream().map(img -> new FinanceOrderImgEntity(add, img)).toList());
        }
        //更新记账分类热度
        FinanceCategoryEntity category = categoryService.getById(entity.getCategoryId());
        category.setHotOrder(category.getHotOrder() + 1);
        categoryService.update(category);
        return add;
    }

    @Override
    public boolean delete(Long... ids) {
        for (Long id : ids) {
            FinanceOrderEntity order = super.getById(id);
            FinanceAccountEntity account = accountService.getById(order.getAccountId());
            if (order.getOrderType().equals(OrderType.EXPEND)){
                //归还账户余额
                account.setAccountBalance(account.getAccountBalance().add(order.getOrderMoney()));
            } else if (order.getOrderType().equals(OrderType.INCOME)) {
                if (account.getAccountBalance().compareTo(order.getOrderMoney())<0){
                    throw new CoolException("当前账户余额不足，无法删除该收入记录");
                }
                //扣除账户余额
                account.setAccountBalance(account.getAccountBalance().subtract(order.getOrderMoney()));
            }
            accountService.updateById(account);
            super.delete(id);
            return true;
        }
        throw new CoolException("删除失败");
    }
}

